﻿using Com.JunCaiSoft.API.Common.Model;
using Com.JunCaiSoft.AutoMapper;
using Com.JunCaiSoft.Common.AssistClass;
using Com.JunCaiSoft.Common.Controller;
using Com.JunCaiSoft.Common.ExchangeData;
using Com.JunCaiSoft.Common.Extension;
using Com.JunCaiSoft.Common.Model;
using Com.JunCaiSoft.Common.Verification;
using Com.JunCaiSoft.Freeze.Dto;
using Com.JunCaiSoft.Freeze.Entity;
using Com.JunCaiSoft.Freeze.IDao;
using Com.JunCaiSoft.Freeze.Model;
using Com.JunCaiSoft.NoticeSystem.Entity;
using Com.JunCaiSoft.WXWork.Common;
using Com.JunCaiSoft.WXWork.RestFul;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Com.JunCaiSoft.API.Freeze.Controllers
{
    /// <summary>
    /// 冻结资金管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class FreezeMoneyController : BaseController<FreezeMoneyView,FreezeMoneyItem, FreezeMoney, Guid>
    {
        /// <summary>
        /// 配置
        /// </summary>
        private IConfiguration Configuration { get; set; }
        /// <summary>
        /// 配置环境
        /// </summary>
        private readonly IWebHostEnvironment HostingEnvironment;
        /// <summary>
        /// APICoreBaseURL
        /// </summary>
        private readonly String APICoreBaseURL;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="freezeMoneyDao"></param>
        public FreezeMoneyController(IFreezeMoneyDao freezeMoneyDao,IWebHostEnvironment env) : base(freezeMoneyDao)
        {
            var builder = new ConfigurationBuilder()
                               .SetBasePath(env.ContentRootPath)
                               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                               .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
                               .AddJsonFile("DataBaseExcute.json", optional: true, reloadOnChange: true);
            HostingEnvironment = env;
            Configuration = builder.Build();
            APICoreBaseURL = Configuration.GetSection("APICores:BaseURL").Value;
        }
        /// <summary>
        /// 按冻结ID单个删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public override async Task<ActionResult> DeleteSingleAsync(Guid Id)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();
                int result = await DaoAsync.DeleteListAsync<FreezeMoney>(x => x.Id == Id);

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DaoAsync.dbContext.Database.CommitTransaction();
            }
        }
        /// <summary>
        /// 按冻结ID批量删除
        /// </summary>
        /// <param name="DeleteList"></param>
        /// <returns></returns>
        [HttpPatch]
        public virtual async Task<ActionResult> DeleteList(IEnumerable<Guid> DeleteList)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();

                int result = await DaoAsync.DeleteListAsync<FreezeMoney>(x => DeleteList.Contains(x.Id));

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DaoAsync.dbContext.Database.CommitTransaction();
            }
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize"></param>
        /// <param name="keyword">关键字</param>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> ListByPageAsync(int pageIndex, int pageSize, String keyword)
        {
            try
            {
                var columns = @" f.Id,
	                             f.Num,
	                             f.NumCode,
                                 pt.NickName BranchCompany,
                                 pt.Boss BranchBoss,
	                             c.Creditor ProjectManager,
                                 c.CreditorID ProjectManagerID,
	                             pj.Name FreezeProject,
                                 b.Name FreezeBank,
                                 b.Account,
	                             f.FreezeConfirm,
	                             p.CaseCode CaseCode,
                                 cs.Name CaseStatus,
	                             f.FactFreeze,
	                             f.Amount,
                                 ft.Name FundsType,
	                             f.FreezeTime,
	                             f.FreezeLoanConfirm,
	                             f.Remark,
	                             u.RealName FreezeOperator,
	                             f.CreateTime ";

                var tables = @" FreezeMoney f
                                LEFT JOIN FundsType ft on f.FundsType = ft.Code
	                            LEFT JOIN Bank b ON f.FreezeBank = b.Id
	                            LEFT JOIN Preservation p ON f.PreservationInfo = p.Id
	                            LEFT JOIN CaseMain cm ON p.CaseMainInfo = cm.Id
                                LEFT JOIN CaseStatus cs on cm.CaseStatus = cs.Code
	                            LEFT JOIN Project pj ON cm.CaseProject = pj.Id
                                LEFT JOIN Partment pt on pj.Partment = pt.Id
	                            LEFT JOIN [User] u ON f.FreezeOperatorId = u.Id
	                            LEFT JOIN CreditContract c ON f.CreditContractInfo = c.Id ";

                var where = @" 1 = 1 ";

                List<SqlParameter> bankParams = new List<SqlParameter>() { };

                if (keyword != "" && keyword != null)
                {

                    Regex rex = new Regex(@"^\d{4}$");

                    if (keyword.Length == 4 && rex.IsMatch(keyword))
                    {
                        where += " AND f.Account like @BankNameOrBankTail ";

                        SqlParameter QueryBankName = new SqlParameter("@BankNameOrBankTail", "%" + keyword);

                        bankParams.Add(QueryBankName);
                    }
                    else
                    {
                        where += " AND b.Name like @BankNameOrBankTail OR p.Name like @BankNameOrBankTail ";

                        SqlParameter QueryBankName = new SqlParameter("@BankNameOrBankTail", "%" + keyword + "%");

                        bankParams.Add(QueryBankName);
                    }

                }

                var tmpResultList = await DaoAsync.QuerySQLByPageQuickAsync<FreezeMoneyItemDto>(pageIndex, pageSize, " f.CreateTime desc ", columns, tables, where, bankParams.Select(x => ((ICloneable)x).Clone()).ToArray());

                var resultList = new QueryData<FreezeMoneyItem>();

                var itemList = new List<FreezeMoneyItem>();

                resultList.totalCount = tmpResultList.totalCount;

                tmpResultList.items.ToList().ForEach(item => itemList.Add(item.MapTo<FreezeMoneyItem>()));

                resultList.items = itemList;

                return await Task.Run(() => Content(JsonConvert.SerializeObject(resultList)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        [HttpGet]
        public override async Task<ActionResult> GetAsync(Guid Id)
        {
            try
            {
                DaoAsync.dbContext.Database.BeginTransaction();

                var result = (await DaoAsync.GetAsync(Id)).MapTo<FreezeMoneyView>();

                DaoAsync.dbContext.Database.CommitTransaction();
                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 创建冻结信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public override async Task<ActionResult> CreateAsync(FreezeMoneyView entity)
        {
            try
            {
                DaoAsync.dbContext.Database.BeginTransaction();

                var saveone = entity.MapTo<FreezeMoney>();
                var result = await DaoAsync.InsertAsync(saveone);

                if (entity.NoticeData != null)
                {
                    entity.NoticeData.ForEach(item => item.SendData = saveone.Id);

                    foreach (var item in entity.NoticeData)
                    {
                        item.Content.textcard.description = item.Title;

                        var sendData = JsonConvert.SerializeObject(new SendTextCardInfo()
                        {
                            body = item.Content,
                            partment = PartmentEnum.财务资金中心
                        });

                        var sendresult = HttpExtension.HttpPost(APICoreBaseURL + "/WXWork/SendMessage/SendTextCardMessage", sendData, true, Request.Headers["Authorization"].ToString());

                        item.NoticeLog = sendresult;

                        await DaoAsync.InsertAsync<Notice>(item.MapTo<Notice>());
                    }
                }

                DaoAsync.dbContext.Database.CommitTransaction();
                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }

        }
        /// <summary>
        /// 更新冻结信息
        /// </summary>
        /// <param name="entityModel"></param>
        /// <returns></returns>
        [HttpPut]
        public override async Task<ActionResult> UpdateAsync(UpdateEntity<FreezeMoneyView> entityModel)
        {
            DaoAsync.dbContext.Database.BeginTransaction();

            var saveone = entityModel.entity.MapTo<FreezeMoney>();
            var result = await DaoAsync.UpdateAsync(saveone, entityModel.Id);

            DaoAsync.dbContext.Database.CommitTransaction();
            return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
        }
        [HttpGet]
        public virtual async Task<ActionResult> CheckIDNumber(String IDnumberStr)
        {
            try
            {
                var str = IDnumber.CheckIDnumber(IDnumberStr);
                return await Task.Run(() => Content(JsonConvert.SerializeObject(str)));
            }
            catch(Exception e)
            {
                return await Task.Run(() => Content(JsonConvert.SerializeObject(e.Message)));
            }
        }
    }
}
